package com.sto.stoapp.db.manager;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.sto.stoapp.db.StoDataBase;
import com.sto.stoapp.db.constant.StoBaseConstant;
import com.sto.stoapp.db.constant.StoProblemConstant;
import com.sto.stoapp.entity.ProblemEntity;
import com.sto.stoapp.http.response.download.info.IssueInfo;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.util.UnifiedStaticType;

/**
 * 问题件数据库
 * 
 * @author mgf
 * 
 */
public class ProblemManager extends StoDataBase implements
		DownLoadDao<IssueInfo> {

	private static ProblemManager problemManager;

	private static final String SQL_QUERY_ALL = "select * from "
			+ PROBLEM_TABLE + " where 1=1";

	private static final String SQL_QUERY_COUNT = "select count(*) from "
			+ PROBLEM_TABLE + " where 1=1";

	private ProblemManager(Context context) {
		super(context);
	}

	/**
	 * 单例化对象
	 * 
	 * @param context
	 * @return
	 */
	public static ProblemManager getInstance(Context context) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			if (problemManager == null) {
				problemManager = new ProblemManager(context);
			}
			return problemManager;
		}
	}

	/**
	 * 插入单条数据
	 * 
	 * @param entity
	 * @return
	 */
	public boolean insert(IssueInfo info) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				String userWidget = "";

				ContentValues values = new ContentValues();
				values.put(TYPE_CODE, info.parentCode);
				values.put(TYPE_NAME, info.parentName);
				values.put(REASON_CODE, info.code);
				values.put(REASON_NAME, info.name);
				String level = info.level;
				if ("01".equals(level))
					userWidget = "A";
				else if ("02".equals(level))
					userWidget = "N";
				else if ("03".equals(level))
					userWidget = "C";
				values.put(USER_WIDGET, userWidget);
				values.put(StoProblemConstant.ID, info.id);
				values.put(StoProblemConstant.STATUS, info.status);
				values.put(StoProblemConstant.VERSION, info.version);
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.insert(PROBLEM_TABLE, null, values);
				if (res > 0) {
					Log.d("插入一条问题件", "成功");
				} else {
					Log.d("插入一条问题件", "失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insert", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}

	/**
	 * 查询问题件的数量
	 * 
	 * @return
	 */
	public int queryAllCount() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			int count = 0;
			Cursor cursor = null;
			try {
				cursor = getSqliteDatabase(UnifiedStaticType.READ_DATABASE)
						.rawQuery(SQL_QUERY_COUNT, null);
				if (cursor != null && cursor.moveToFirst()) {
					count = cursor.getInt(0);
				}
				closeCursor(cursor);
			} finally {
				closeCursor(cursor);
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return count;
		}
	}

	/**
	 * 查询所有数据
	 * 
	 * @return
	 */
	public List<ProblemEntity> queryAll() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			List<ProblemEntity> data = getDataFromCursor(getSqliteDatabase(
					UnifiedStaticType.READ_DATABASE).rawQuery(SQL_QUERY_ALL,
					null));
			return data;
		}
	}

	private List<ProblemEntity> getDataFromCursor(final Cursor c) {
		List<ProblemEntity> lstData = new ArrayList<ProblemEntity>();
		if (c != null) {
			if (c.moveToFirst()) {
				do {
					lstData.add(getSingleData(c));
				} while (c.moveToNext());
			}
			closeCursor(c);
		}
		closeDb(UnifiedStaticType.READ_DATABASE);
		return lstData;
	}

	private ProblemEntity getSingleData(Cursor c) {
		ProblemEntity data = new ProblemEntity();
		data.setTypeCode(c.getString(c.getColumnIndex(TYPE_CODE)));
		data.setTypeName(c.getString(c.getColumnIndex(TYPE_NAME)));
		data.setReasonCode(c.getString(c.getColumnIndex(REASON_CODE)));
		data.setReasonDetail(c.getString(c.getColumnIndex(REASON_NAME)));
		data.setUserWidget(c.getString(c.getColumnIndex(USER_WIDGET)));
		return data;
	}

	@Override
	public String getMaxVersion() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			String version = "0";
			Cursor c = null;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
				c = db.rawQuery(getMaxVersionSql(PROBLEM_TABLE), null);
				if (c != null && c.moveToNext()) {
					version = c.getString(c
							.getColumnIndex(StoBaseConstant.VERSION));
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeCursor(c);
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return version;
		}
	}

	@Override
	public boolean replace(ContentValues values) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long result = 0;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				result = db.replace(PROBLEM_TABLE, null, values);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result > 0;
		}
	}

	@Override
	public void deleteDataByStatus(String status) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {

			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				db.delete(PROBLEM_TABLE, STATUS + "=?", new String[] { status });
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}
	}

	@Override
	public ContentValues buildContentValues(IssueInfo entity) {
		ContentValues values = new ContentValues();
		values.put(TYPE_CODE, entity.parentCode);
		values.put(TYPE_NAME, entity.parentName);
		values.put(REASON_CODE, entity.code);
		values.put(REASON_NAME, entity.name);
		values.put(StoProblemConstant.LEVEL, entity.level);
		String userWidget = "";
		String attribute = entity.attribute;
		if ("全部".equals(attribute))
			userWidget = "A";
		else if ("网点".equals(attribute))
			userWidget = "N";
		else if ("中心".equals(attribute))
			userWidget = "C";
		values.put(USER_WIDGET, userWidget);
		values.put(StoProblemConstant.ID, entity.id);
		values.put(StoProblemConstant.STATUS, entity.status);
		values.put(StoProblemConstant.VERSION, entity.version);
		return values;
	}

	/**
	 * 插入多数据
	 * 
	 * @param entity
	 * @return
	 */
	@Override
	public void insertOrReplace(List<IssueInfo> datas) {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				for (IssueInfo info : datas) {
					long res = -1;
					ContentValues values = buildContentValues(info);
					// res = db.insert(PROBLEM_TABLE, null, values);
					// if (res > 0) {
					// Log.d("插入一条问题件", "成功");
					// } else {
					if (replace(values)) {
						Log.d("插入一条问题件", "成功");
					} else {
						Log.d("插入一条问题件", "失败");
						// }
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insertList", e.getMessage());
			} finally {
				datas.clear();
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
		}
	}

	@Override
	public void deleteAll() {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.delete(PROBLEM_TABLE, null, null);
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteAll", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}

	}
}
